<template>
  <view class="detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"></uni-load-more>
    </view>

    <!-- 日志详情内容 -->
    <view v-else-if="logInfo" class="content-container">
      <!-- 基本信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="person" size="16" color="#007aff"></uni-icons>
          <text class="title-text">基本信息</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">访问编号：</text>
            <text class="info-value">{{ logInfo.infoId }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">用户名称：</text>
            <text class="info-value user-name">{{ logInfo.userName }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">登录状态：</text>
            <uni-tag
                :text="logInfo.status === '0' ? '成功' : '失败'"
                :type="logInfo.status === '0' ? 'success' : 'error'"
                size="small">
            </uni-tag>
          </view>
          <view class="info-row">
            <text class="info-label">登录时间：</text>
            <text class="info-value">{{ parseTime(logInfo.loginTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 网络信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="globe" size="16" color="#007aff"></uni-icons>
          <text class="title-text">网络信息</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">登录地址：</text>
            <text class="info-value ip-text">{{ logInfo.ipaddr }}</text>
            <button class="copy-btn" size="mini" @click="handleCopy(logInfo.ipaddr, 'IP地址')">
              <uni-icons type="copy" size="12"></uni-icons>
            </button>
          </view>
          <view class="info-row" v-if="logInfo.loginLocation">
            <text class="info-label">登录地点：</text>
            <text class="info-value">{{ logInfo.loginLocation }}</text>
          </view>
        </view>
      </view>

      <!-- 设备信息 -->
      <view class="info-section" v-if="logInfo.os || logInfo.browser">
        <view class="section-title">
          <uni-icons type="gear" size="16" color="#007aff"></uni-icons>
          <text class="title-text">设备信息</text>
        </view>
        <view class="info-content">
          <view class="info-row" v-if="logInfo.os">
            <text class="info-label">操作系统：</text>
            <text class="info-value">{{ logInfo.os }}</text>
          </view>
          <view class="info-row" v-if="logInfo.browser">
            <text class="info-label">浏览器：</text>
            <text class="info-value">{{ logInfo.browser }}</text>
          </view>
        </view>
      </view>

      <!-- 登录结果 -->
      <view class="info-section" v-if="logInfo.msg">
        <view class="section-title">
          <uni-icons type="chat" size="16" color="#007aff"></uni-icons>
          <text class="title-text">登录结果</text>
        </view>
        <view class="message-content" :class="{ 'error-content': logInfo.status === '1' }">
          <text class="message-text">{{ logInfo.msg }}</text>
        </view>
      </view>

      <!-- 安全提醒 -->
      <view class="info-section security-section" v-if="logInfo.status === '1'">
        <view class="section-title">
          <uni-icons type="info" size="16" color="#ff4d4f"></uni-icons>
          <text class="title-text">安全提醒</text>
        </view>
        <view class="security-content">
          <view class="security-item">
            <uni-icons type="closeempty" size="16" color="#ff4d4f"></uni-icons>
            <text class="security-text">该用户登录失败，请检查是否存在安全风险</text>
          </view>
          <view class="security-item" v-if="getFailureCount() > 1">
            <uni-icons type="info" size="16" color="#ff4d4f"></uni-icons>
            <text class="security-text">检测到多次登录失败，建议进行安全审查</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <view class="action-buttons">
          <button class="unlock-btn" type="primary" @click="handleUnlock" v-if="logInfo.status === '1'">
            <uni-icons type="locked" size="16" color="#fff"></uni-icons>
            解锁用户
          </button>
          <button class="delete-btn" type="default" @click="handleDelete">
            <uni-icons type="trash" size="16" color="#ff4d4f"></uni-icons>
            删除日志
          </button>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <uni-icons type="info" size="40" color="#ccc"></uni-icons>
      <text class="error-text">日志不存在或已被删除</text>
      <button class="retry-btn" @click="getLogDetail">重新加载</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {delLoginInfo, list, unlockLoginInfo} from '@/api/monitor/loginInfo'
import {parseTime} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 数据定义
const logInfo = ref(null)
const loading = ref(true)
const infoId = ref('')

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  if (options.infoId) {
    infoId.value = options.infoId
    getLogDetail()
  } else {
    loading.value = false
    proxy.$modal.showToast('缺少日志ID参数')
  }
})

// 获取日志详情
async function getLogDetail() {
  loading.value = true

  try {
    // 通过列表接口获取单条数据详情
    const response = await list({infoId: infoId.value})
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      logInfo.value = response.rows[0]
    } else {
      logInfo.value = null
      proxy.$modal.showToast('获取日志详情失败')
    }
  } catch (error) {
    console.error('获取日志详情失败:', error)
    logInfo.value = null
    proxy.$modal.showToast('获取日志详情失败')
  } finally {
    loading.value = false
  }
}

// 获取失败次数（模拟）
function getFailureCount() {
  // 这里可以根据实际需求调用接口获取该用户的失败次数
  return Math.floor(Math.random() * 5) + 1
}

// 解锁用户
async function handleUnlock() {
  if (!logInfo.value) return

  const result = await proxy.$modal.confirm(`是否确认解锁用户"${logInfo.value.userName}"？`)
  if (result) {
    try {
      const response = await unlockLoginInfo(logInfo.value.userName)
      if (response.code === 200) {
        proxy.$modal.showToast(`用户"${logInfo.value.userName}"解锁成功`)
        // 刷新页面数据
        getLogDetail()
      } else {
        proxy.$modal.showToast(response.msg || '解锁失败')
      }
    } catch (error) {
      console.error('解锁失败:', error)
      proxy.$modal.showToast('解锁失败')
    }
  }
}

// 删除日志
async function handleDelete() {
  if (!logInfo.value) return

  const result = await proxy.$modal.confirm(`是否确认删除访问编号为"${logInfo.value.infoId}"的数据项？`)
  if (result) {
    try {
      const response = await delLoginInfo(logInfo.value.infoId)
      if (response.code === 200) {
        proxy.$modal.showToast('删除成功')
        setTimeout(() => {
          handleBack()
        }, 1500)
      } else {
        proxy.$modal.showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      proxy.$modal.showToast('删除失败')
    }
  }
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/detail-page.scss';
</style>